package com.lyf.language.practice.practice_6_21.io.network.tcpv1;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * 只能实现--逐一回复、对话
 *
 * -- 多线程分离 in,out,实现无需逐一回复
 * @author LYF
 * @date 2022/6/22
 */
public class TcpSocketServer {

    /**
     * 服务端程序
     */
    public void server() throws IOException {

        Scanner scanner = new Scanner(System.in);

        // 服务端监听 8888 端口
        ServerSocket serverSocket = new ServerSocket(8888);
        System.out.println("waiting connecting");
        Socket client = serverSocket.accept();
        System.out.println("connected successfully ( enter exit to end communicate)");

        boolean flag = false;

        Thread thread = new Thread(()->{


        });


        // 一直监听IO流中的信息
        while (true) {
            // 获取客户端输入流
            InputStream inputStream = client.getInputStream();
            byte[] bytes = new byte[1024];// 对于字节数较少，则直接--开大一点--一次性读取
            int read = inputStream.read(bytes);

            if(read!=-1)
               // 客户端发来的消息
               System.out.println("client-"+client.getRemoteSocketAddress()+":" +
                    new String(bytes, 0, read, Charset.defaultCharset()));

            // 给客户端发端东西
            System.out.print("reply:");
            // String nextLine = scanner.next();
            String nextLine = scanner.nextLine();
            if ("exit".equals(nextLine)) {
                break;
            }
            OutputStream outputStream = client.getOutputStream();
            outputStream.write(nextLine.getBytes(StandardCharsets.UTF_8));


        }
    }

    public static void main(String[] args) throws IOException {
        TcpSocketServer tcpSocketServer = new TcpSocketServer();
        tcpSocketServer.server();;
    }
}
